<template>
  <el-dialog
    title="分配角色"
    :visible="showRoleDialog"
    :before-close="handleCloseThis"
  >
    <!-- el-checkbox-group选中的是 当前用户所拥有的角色  需要绑定 当前用户拥有的角色-->
    <el-checkbox-group v-model="checkList">
      <!-- 选项 -->
      <el-checkbox v-for="item in allRoles" :key="item.id" :label="item.id">{{
        item.name
      }}</el-checkbox>
    </el-checkbox-group>
    <!-- 控件 -->
    <template #footer>
      <el-row type="flex" justify="center">
        <el-col :span="6">
          <el-button
            type="primary"
            size="small"
            @click="handleAssign"
          >确定</el-button>
          <el-button size="small" @click="handleCloseThis">取消</el-button>
        </el-col>
      </el-row>
    </template>
  </el-dialog>
</template>

<script>
import { getRolesAPI } from '@/api/roles'
import { getUserInfoByIdAPI, assignUserRoleAPI } from '@/api/user'

export default {
  props: {
    showRoleDialog: {
      type: Boolean,
      default: false
    },
    userId: {
      type: String,
      default: '',
      required: true
    }
  },
  data() {
    return {
      allRoles: [], // 角色列表
      checkList: [] // 选中列表
    }
  },
  // 用户id变化时重新获取权限
  watch: {
    userId(id) {
      this.getUserRolesFn(id)
    }
  },
  created() {
    this.getRolesFn()
  },
  methods: {
    // 获取全部角色列表
    async getRolesFn() {
      try {
        const { rows } = await getRolesAPI({ page: 1, pagesize: 999 })
        this.allRoles = rows
      } catch (e) {
        console.log(e)
      }
    },

    // 获取当前用户角色
    async getUserRolesFn(id) {
      try {
        const { roleIds } = await getUserInfoByIdAPI(id)
        this.checkList = [...roleIds]
        // console.log(this.checkList)
      } catch (e) {
        console.log(e)
      }
    },

    // 关闭弹层
    handleCloseThis() {
      this.$emit('update:showRoleDialog', false)
    },

    // 提交
    async handleAssign() {
      try {
        await assignUserRoleAPI({ id: this.userId, roleIds: this.checkList })
        this.$message.success('操作成功')
        this.handleCloseThis()
      } catch (e) {
        this.$message.info(e)
      }
    }
  }
}
</script>
